﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;

using Log;

namespace ilibrary.source.model
{
    /// <summary>
    /// Classe factory chargeant au démarrage les handlers disponibles dans le dossier handlers.
    /// </summary>
    public class EbookHandlerFactory
    {
        private EventLog log = new EventLog("ILibrary", "EbookHandlerFactory");
        private Dictionary<string, IEbookHandler> ebookHandlers = new Dictionary<string, IEbookHandler>();

        private static EbookHandlerFactory factory = new EbookHandlerFactory();

        public static EbookHandlerFactory Instance
        {
            get
            {
                return factory;
            }
        }

        protected EbookHandlerFactory()
        {
            LoadEbookHandlers();
        }

        public List<string> GetAllSupportedFormats()
        {
            try
            {
                List<string> list = new List<string>();
                foreach (string key in ebookHandlers.Keys)
                {
                    list.Add(key);
                }
                return list;
            }
            catch (Exception ex)
            {
                log.Error("", ex);
                return new List<string>();
            }
        }

        /// <summary>
        /// Retourne le handler gérant le fichier spécifié.
        /// Si cette extension n'est pas supportée, null est retournée.
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public IEbookHandler GetHandlerFromPath(string path)
        {
            string ext = System.IO.Path.GetExtension(path);
            return GetHandler(ext);
        }

        /// <summary>
        /// Retourne le handler gérant l'extension spécifiée
        /// Si cette extension n'est pas supportée, null est retournée.
        /// </summary>
        /// <param name="extension"></param>
        /// <returns></returns>
        public IEbookHandler GetHandler(string extension)
        {
            try
            {
                if (extension == null)
                    return null;
                if (ebookHandlers.ContainsKey(extension.ToLower()))
                    return ebookHandlers[extension.ToLower()];
            }
            catch (Exception ex)
            {
                this.log.Error("", ex);
            }
            return null;
        }

        /// <summary>
        /// Ouvre le dossier handlers et charge dans les dlls toutes les classes
        /// implémentant IEbookHandler
        /// </summary>
        private void LoadEbookHandlers()
        {
            try
            {
                string[] files = System.IO.Directory.GetFiles(System.IO.Path.GetFullPath("handlers"), "*Handler.dll");
                foreach (string path in files)
                {
                    Assembly engine = null;
                    AssemblyName assemblyName = new AssemblyName();
                    assemblyName.CodeBase = path;
                    engine = Assembly.Load(assemblyName);
                    Type[] types = engine.GetTypes();
                    foreach (Type type in types)
                    {
                        try
                        {
                            if ((type.IsClass) && (type.GetInterface(typeof(IEbookHandler).FullName) != null))
                            {
                                ConstructorInfo ci = type.GetConstructor(Type.EmptyTypes);
                                IEbookHandler handler = (IEbookHandler)ci.Invoke(null);
                                ebookHandlers.Add(handler.getSupportedExtension(), handler);
                            }
                        }
                        catch (Exception ex)
                        {
                            log.Warn("", ex);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                log.Error("", ex);
            }
        }
    }
}
